package com.xuexuehai.bkm.service.user.admin.service.impl;

import com.xuexuehai.bkm.core.common.constants.RespConstants;
import com.xuexuehai.bkm.core.common.constants.SystemConstants;
import com.xuexuehai.bkm.core.common.exception.security.InvalidUserException;
import com.xuexuehai.bkm.core.common.exception.security.UsernameIsEmptyException;
import com.xuexuehai.bkm.core.common.exception.security.UsernameNotFoundException;
import com.xuexuehai.bkm.domain.entity.Admin;
import com.xuexuehai.bkm.service.user.admin.dao.IAdminDao;
import com.xuexuehai.bkm.service.user.admin.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * @author xuexuehai
 * @mailBox xuehai.xue@QQ.com
 * @date 2021/9/11 2:36 下午
 */
@Service
@Transactional
public class AdminServiceImpl implements IAdminService {

    @Autowired
    private IAdminDao iAdminDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    /*
//     * redis 预热
//     */
//    {
//        Set<String> set = iAdminDao.findAllNums();
//        stringRedisTemplate.opsForSet().add("admin_nums",set.toArray(new String[set.size()]));
//    }

    @Override
    public Admin login(String username, String password) {
        if(null == username || "".equals(username)) {
            throw new UsernameIsEmptyException(RespConstants.USERNAME_IS_EMPTY);
        }
        if(!stringRedisTemplate.opsForSet().isMember(SystemConstants.REDIS_ADMIN_NUM,username)){
            throw new UsernameNotFoundException(RespConstants.USERNAME_NOT_FOUND);
        }

        Admin admin = iAdminDao.findByNumAndPassword(username,password);

        if(admin == null){
            throw new InvalidUserException(RespConstants.INLAID_USER);
        }
        return admin;
    }
}
